/**
 * @author		Sergey Suzdalskiy
 * @e-mail:		sergey.suzdalskiy@gmail.com
 */
package ua.kiev.gcore.net.command
{
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	
	import ua.kiev.gcore.logger.Logger;

	public class ProtocolParserBase implements IProtocolParser
	{
		private const sizeNone:int = -1;
		
		private var buffer:ByteArray;
		private var size:int;
		
		public function ProtocolParserBase():void{
			
			buffer = new ByteArray();
			buffer.endian = Endian.LITTLE_ENDIAN;
			size = sizeNone;
		}
		
		public function parse(command:Object):void
		{
			Logger.INFO("[CommandParserBase] parse");
			if((command == null) ||  !(command is ByteArray)){
				Logger.ERROR("[CommandParserBase] invalid parse data type");
				return;
			}
			
			var bytes:ByteArray = command as ByteArray;
			
			while(bytes.bytesAvailable){
				if(size == sizeNone){
					if(bytes.bytesAvailable < 4){
						buffer.position = buffer.length;
						buffer.writeBytes(bytes, bytes.position)
						bytes.clear();
						buffer.position = 0;
						return;
					}
					size = bytes.readInt();
					Logger.INFO("[CommandParserBase] package size: ", size);
				}
				
				buffer.position = buffer.length;
				buffer.writeBytes(bytes, bytes.position)
				bytes.clear();
				buffer.position = 0;
				
				if(buffer.length < size){
					return;
				}else{				
					var data:ByteArray = new ByteArray();
					data.endian = Endian.LITTLE_ENDIAN;
					buffer.readBytes(data, 0, size);
					size = sizeNone;
					
					parsePackage(data);
					
					if(buffer.bytesAvailable){
						buffer.readBytes(bytes);	
					}
					buffer.clear();
				}	
			}
		}
		
		protected function parsePackage(packageData:ByteArray):void{
			Logger.INFO("[CommandParserBase] parsePackage");
			if(packageData.bytesAvailable < 5){
				Logger.ERROR("[CommandParserBase] invalid package size");
				return;
			}
			
			var format:int = packageData.readInt();
			var commandId:int = packageData.readInt();
			var status:int =  packageData.readByte();
			
			var commandData:ByteArray = new ByteArray();
			commandData.endian = Endian.LITTLE_ENDIAN;
			
			packageData.readBytes(commandData);
			
			Logger.DEBUG("[Server] commandId:", commandId, "; status: ", status, "; format: ", format, ";");
			
			parseCommand(commandData, status, commandId, format)
		}
		
		protected function parseCommand(commandData:ByteArray, status:int, commandId:int, format:int):void{
			Logger.INFO("[CommandParserBase] parseCommand");
		}
		
	}
}